<template>
  <!-- 完成excel文件的导入，从硬盘到浏览器内存，就会执行 -->
  <UploadExcel :on-success="handleSuccess" />
</template>

<script>
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'
export default {
  name: 'Import',
  methods: {
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log(res)
        this.$message.success('导入成功')
        // 页面后退
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$message.success('导入失败')
      }
    },
    handleSuccess({ header, results }) {
      console.log(header, results)
      // 按接口要求组装数据
      const data = this.transExcel(results)
      console.log(data)
      this.doImport(data)
    },
    transExcel(results) {
      const mapinfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhobj => {
        const enObj = {}
        // 取出obj中文的key
        const zhkeys = Object.keys(zhobj)
        zhkeys.forEach(zhkey => {
          const enkey = mapinfo[zhkey]
          console.log(enkey)
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            enObj[enkey] = new Date(formatExcelDate(zhobj[zhkey]))
          } else {
            enObj[enkey] = zhobj[zhkey]
          }
        })
        return enObj
      })
    }
  }
}
</script>
